package com.lewis.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lewis.core.base.domain.entity.SysUser;
import com.lewis.core.constant.UserConstants;
import com.lewis.core.exception.CustomException;
import com.lewis.core.exception.ServiceException;
import com.lewis.core.utils.DateUtil;
import com.lewis.core.utils.SecurityUtil;
import com.lewis.core.utils.SpringUtil;
import com.lewis.core.utils.StringUtil;
import com.lewis.system.mapper.SysUserMapper;
import com.lewis.system.service.ISysConfigService;
import com.lewis.system.service.ISysUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hpsf.Array;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * 用户 业务层处理
 *
 * @author Lewis
 */
@Slf4j
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements ISysUserService {

	@Resource
	private SysUserMapper sysUserMapper;

	@Resource
	private ISysConfigService sysConfigService;

	@Override
	public void checkUserDataScope(Long userId) {
		if (!SysUser.isAdmin(SecurityUtil.getUserId())) {
			SysUser user = new SysUser();
			user.setId(userId);
			List<SysUser> users = SpringUtil.getAopProxy(this).selectUserList(user);
			if (StringUtil.isEmpty(users)) {
				throw new ServiceException("没有权限访问用户数据！");
			}
		}
	}

	public boolean registerUser(SysUser user) {
		return sysUserMapper.insert(user) > 0;
	}

	@Override
	public List<SysUser> selectUserList(SysUser user) {
		LambdaQueryWrapper<SysUser> lqw = new LambdaQueryWrapper<SysUser>()
				.eq(SysUser::getDelFlag, "0")
				.like(StringUtil.isNotEmpty(user.getUserName()), SysUser::getUserName, user.getUserName())
				.like(StringUtil.isNotEmpty(user.getUserType()), SysUser::getUserType, user.getUserType())
				.eq(StringUtil.isNotEmpty(user.getStatus()), SysUser::getStatus, user.getStatus())
				.like(StringUtil.isNotEmpty(user.getPhoneNumber()), SysUser::getPhoneNumber, user.getPhoneNumber());

		Map<String, Object> params = user.getParams();
		if (params != null) {
			Object beginTime = user.getParams().get("beginTime");
			if (beginTime != null) {
				lqw.ge(StringUtil.isNotEmpty(String.valueOf(DateUtil.parseDate(user.getParams().get("beginTime")))), SysUser::getCreateTime, String.valueOf(DateUtil.parseDate(user.getParams().get("beginTime"))));
			}
			Object endTime = user.getParams().get("endTime");
			if (endTime != null) {
				lqw.le(StringUtil.isNotEmpty(String.valueOf(DateUtil.parseDate(user.getParams().get("endTime")))), SysUser::getCreateTime, String.valueOf(DateUtil.parseDate(user.getParams().get("endTime"))));
			}
		}

		return sysUserMapper.selectList(lqw);
	}

	@Override
	public String checkUserNameUnique(String userName) {

		int count = sysUserMapper.selectCount(
				new LambdaQueryWrapper<SysUser>()
						.eq(SysUser::getUserName, userName)
						.last("limit 1")
		);

		if (count > 0) {
			return UserConstants.NOT_UNIQUE;
		}
		return UserConstants.UNIQUE;
	}

	@Override
	public String checkPhoneUnique(SysUser user) {
		Integer info = sysUserMapper.selectCount(
				new LambdaQueryWrapper<SysUser>()
						.eq(SysUser::getPhoneNumber, user.getPhoneNumber())
						.last("limit 1")
		);

		return info > 0 ? UserConstants.NOT_UNIQUE : UserConstants.UNIQUE;
	}

	@Override
	public String checkEmailUnique(SysUser user) {
		Integer info = sysUserMapper.selectCount(
				new LambdaQueryWrapper<SysUser>()
						.eq(SysUser::getEmail, user.getEmail())
						.last("limit 1")
		);

		return info > 0 ? UserConstants.NOT_UNIQUE : UserConstants.UNIQUE;
	}

	@Override
	public void checkUserAllowed(SysUser user) {
		if (StringUtil.isNotNull(user.getId()) && user.isAdmin()) {
			throw new CustomException("不允许操作超级管理员用户");
		}
	}

	@Override
	@Transactional
	public int insertUser(SysUser user) {
		// 新增用户信息
		return sysUserMapper.insert(user);
	}

	@Override
	@Transactional
	public int updateUser(SysUser user) {
		return sysUserMapper.updateById(user);
	}

	@Override
	public int updateUserStatus(SysUser user) {
		return this.updateUser(user);
	}

	@Override
	public int updateUserProfile(SysUser user) {
		return this.updateUser(user);
	}

	@Override
	public boolean updateUserAvatar(String userName, String avatar) {
		SysUser sysUser = new SysUser();
		sysUser.setAvatar(avatar);
		return sysUserMapper.update(
				sysUser,
				new LambdaUpdateWrapper<SysUser>()
						.eq(SysUser::getUserName, userName)
		) > 0;
	}

	@Override
	public int resetPwd(SysUser user) {
		return this.updateUser(user);
	}

	@Override
	public int resetUserPwd(String userName, String password) {
		SysUser sysUser = new SysUser();
		sysUser.setPassword(password);
		return sysUserMapper.update(
				sysUser,
				new LambdaUpdateWrapper<SysUser>().eq(SysUser::getUserName, userName)
		);
	}

	@Override
	@Transactional
	public int deleteUserByIds(Long[] ids) {
		for (Long id : ids) {
			checkUserAllowed(new SysUser(id));
		}

		SysUser sysUser = new SysUser();
		sysUser.setDelFlag("2");

		return sysUserMapper.update(sysUser, new LambdaUpdateWrapper<SysUser>().in(SysUser::getId, Arrays.asList(ids)));
	}

	@Override
	public String importUser(List<SysUser> userList, Boolean isUpdateSupport, String operName) {
		if (StringUtil.isNull(userList) || userList.size() == 0) {
			throw new CustomException("导入用户数据不能为空！");
		}
		int successNum = 0;
		int failureNum = 0;
		StringBuilder successMsg = new StringBuilder();
		StringBuilder failureMsg = new StringBuilder();
		String password = sysConfigService.selectConfigByKey("sys.user.initPassword");
		for (SysUser user : userList) {
			try {
				// 验证是否存在这个用户
				SysUser u = sysUserMapper.selectOne(
						new LambdaQueryWrapper<SysUser>()
								.eq(SysUser::getUserName, user.getUserName())
				);
				if (StringUtil.isNull(u)) {
					user.setPassword(SecurityUtil.encryptPassword(password));
					user.setCreateBy(operName);
					this.insertUser(user);
					successNum++;
					successMsg.append("<br/>").append(successNum).append("、账号 ").append(user.getUserName()).append(" 导入成功");
				} else if (isUpdateSupport) {
					user.setUpdateBy(operName);
					this.updateUser(user);
					successNum++;
					successMsg.append("<br/>").append(successNum).append("、账号 ").append(user.getUserName()).append(" 更新成功");
				} else {
					failureNum++;
					failureMsg.append("<br/>").append(failureNum).append("、账号 ").append(user.getUserName()).append(" 已存在");
				}
			} catch (Exception e) {
				failureNum++;
				String msg = "<br/>" + failureNum + "、账号 " + user.getUserName() + " 导入失败：";
				failureMsg.append(msg).append(e.getMessage());
				log.error(msg, e);
			}
		}
		if (failureNum > 0) {
			failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
			throw new CustomException(failureMsg.toString());
		} else {
			successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
		}
		return successMsg.toString();
	}

}
